<?php
/**
 * Created by 绵阳人维网络科技有限公司.
 * User: 罗东华
 * Date: 2016/4/21
 * Time: 14:18
 */
namespace   Admin\Model;
class ModelModel extends AdminModelBase{
    private $libPath =MODULE_PATH ; //当前模块路径

    const ldh_tablename = 'Data/Sql/ldh_tablename.sql'; //模型主表SQL模板文件
    const ldh_tablename_data = 'Data/Sql/ldh_tablename_data.sql'; //模型副表SQL模板文件
    const ldh_model_field = 'Data/Sql/ldh_model_field.sql'; //可用默认模型字段


    public function Model_add($tablename){
       $modelid=$this->db_add();
        if($modelid){
            $res=$this->createModel($tablename,$modelid);
            if($res){return true;}else{
                $this->where(array('modelid'=>$modelid))->delete();
                return false;
            }
        }else{
            return false;
        }

    }
    /**
     * 创建内容模型
     * @param type $tableName 模型主表名称（不包含表前缀）
     * @param type $modelId 模型id
     * @return boolean
     */
    protected function createModel($tableName, $modelId) {
        if (empty($tableName) || $modelId < 1) {
            return false;
        }
        //表前缀
        $dbPrefix = C("DB_PREFIX");
        //读取模型主表SQL模板
        $ldh_tablenameSql = file_get_contents($this->libPath . self::ldh_tablename);
        //副表
        $ldh_tablename_dataSql = file_get_contents($this->libPath . self::ldh_tablename_data);
        //字段数据
        $ldh_model_field = file_get_contents($this->libPath . self::ldh_model_field);
        //表前缀，表名，模型id替换
        $sqlSplit = str_replace(array('@ldh@', '@tablename@', '@modelid@'), array($dbPrefix, $tableName, $modelId), $ldh_tablenameSql . "\n" . $ldh_tablename_dataSql . "\n" . $ldh_model_field);

        return $this->sql_execute($sqlSplit);
    }

    /**
     * 执行SQL
     * @param type $sqls SQL语句
     * @return boolean
     */
    protected function sql_execute($sqls) {
        $sqls = $this->sql_split($sqls);
        if (is_array($sqls)) {
            foreach ($sqls as $sql) {
                if (trim($sql) != '') {
                    $this->execute($sql, true);
                }
            }
        } else {
            $this->execute($sqls, true);
        }
        return true;
    }

    /**
     * SQL语句预处理
     * @param type $sql
     * @return type
     */
    public function sql_split($sql) {
        if (mysql_get_server_info() > '4.1' && C('DB_CHARSET')) {
            $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=" . C('DB_CHARSET'), $sql);
        }
        if (C("DB_PREFIX") != "shuipfcms_") {
            $sql = str_replace("shuipfcms_", C("DB_PREFIX"), $sql);
        }
        $sql = str_replace("\r", "\n", $sql);
        $ret = array();
        $num = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset($sql);
        foreach ($queriesarray as $query) {
            $ret[$num] = '';
            $queries = explode("\n", trim($query));
            $queries = array_filter($queries);
            foreach ($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-')
                    $ret[$num] .= $query;
            }
            $num++;
        }
        return $ret;
    }

    /*删除模型*/
    public function del_model($id){
        if(!$id){return false;}
        $where['modelid']=$id;
        $dbPrefix = C("DB_PREFIX");
        $tablename=$this->where($where)->getField('tablename');
        $this->where($where)->delete();
        M('model_field')->where($where)->delete();
        $sql="DROP TABLE `".$dbPrefix.$tablename.'`';
        $sql2="DROP TABLE `".$dbPrefix.$tablename."_data`";
        $this->execute($sql);
        $this->execute($sql2);
        return true;

    }


}